<template>
  <div class="page_root" :key="queryUpdateFlag" data-page-name="测试免登录" data-page-identification="k_fyt333vxtm">
    <a-spin :spinning="pageLoading.loading" :tip="pageLoading.tip">
      <!-- begin vid_89cbcevsux 自定义模板_676z2luj2z -->
      <div>
        {{ stateForm }}
      </div>
      <!-- end vid_89cbcevsux 自定义模板_676z2luj2z -->
    </a-spin>
  </div>
</template>
<script setup lang="tsx">
  import {
      h, ref, reactive, toRaw, markRaw, watch, computed,
      onBeforeMount, onMounted, onBeforeUnmount, onUnmounted, onActivated, onDeactivated
    } from "vue";
    import { useRoute, useRouter } from 'vue-router';
    const router = useRouter();
    const route = useRoute();
    import { get, post, put, del, request, requestWithHeaders } from '@/utils/http/Axios';
    import { cloneDeep, localGet, merge, getDifferenceArray, traversalTreeStructure, checkCaseCondition, renderStringInTemplate, handleBreadcrumbJump, throttle, permission, getComponentParamsValue } from '@/utils/index';
    import { isNullOrEmpty, isEmptyArr, isNullOrUnDef, isContained, isArray, isEmpty, isObject } from '@/utils/is';
    import dayjs from 'dayjs';
    import { getPagePcChartsDataSourceConvert } from '@/utils/chart';
    import { message, notification, Modal } from 'ant-design-vue'
    import { propertyFormatByNumber, propertyFormatByPercentage, propertyFormatByDate, parseSubFromDataList } from '@/utils/format';
    import colorTheme from '@/design/custom-theme.json';
    
    import UserTableRecords from '@/model/UserTableRecords';
    import { getAppBaseUrl } from '@/utils/index';
    import { sendToken } from "@/hooks/useIframeToken";
    import { useSystemStore } from "@/store/modules/system";
    const systemStore = useSystemStore();
    



      // 获取传入的流程ID和组件参数
      const props = defineProps({
            'processInstanceId': {
            type: [String,Number,Boolean],
            default: undefined,
        },
      })
      const immediateWatch = (source, callback) => {
        watch(source, callback, {deep: true,immediate: true })
      }



  /* -------------------------- 属性定义 -------------------------- */

      const setTimeOutList = [];
      const pageLoading = reactive({
        loading: false,
        tip: undefined
      });
      const authInfo = localGet('app-user-store');




      // 处理校验
      const setSubFormName =(parentInfo, name)=>{
        return [parentInfo.parents, parentInfo.cycleIndex, name];
      }


  /* ========================== 属性定义 ========================== */


  /* -------------------------- 元素数据引用 -------------------------- */


  /* ========================== 元素数据引用 ========================== */


  /* -------------------------- 页面数据 -------------------------- */


  /* ========================== 页面数据 ========================== */



  /* -------------------------- 响应 -------------------------- */

  /* ========================== 响应 ========================== */


  /* -------------------------- 函数 -------------------------- */

  /* ========================== 函数 ========================== */


  /* -------------------------- 页面参数 -------------------------- */

    const pageParameter_state = reactive({
        'processInstanceId': props.processInstanceId ?? route.query.processInstanceId,
    })

  /* ========================== 页面参数 ========================== */


  /* -------------------------- 组件事件处理方法 -------------------------- */

    // ---------------------------- 组件数据同步 ----------------------------

    // ============================ 组件数据同步 ============================


  /* ========================== 组件事件处理方法 ========================== */


  /* -------------------------- 生命周期 -------------------------- */
  // 用于参数变更后重新执行自定义指令
      const queryUpdateFlag = ref(0);
      onMounted(() => { ;

    });

    onUnmounted(() => {
      // 销毁定时器
      setTimeOutList.forEach(({ repeat, timer }) => {
        repeat ?  clearInterval(timer): clearTimeout(timer);
      });
    });

  /* ========================== 生命周期 ========================== */


  /* -------------------------- 数据关联处理 -------------------------- */





  /* -------------------------- 表单数据同步 -------------------------- */
  /* ========================== 表单数据同步 ========================== */

  /* ========================== 数据关联处理 ========================== */


  /* -------------------------- 不同组件自定义的处理逻辑 -------------------------- */

  /* ========================== 不同组件自定义的处理逻辑 ========================== */


  // ================================定制化逻辑========================================
   const stateForm = reactive({
            tenantId: null,
            sessionKey: null,
            userId: null,
            mobile: null,
            productId: null,
            getTidUrl: null,
            newUrl: null
        })
        const debuggerState = reactive({
            first: {
                status: '',
                content: ''
            },
            two: {
                status: '',
                content: ''
            },
            three: {
                status: '',
                content: ''
            },
            four: {
                status: '',
                content: ''
            },
            five: {
                status: '',
                content: ''
            }
        })
        var currentURL = window.location.href
        // var currentURL ='http://asa-qa.allintechinc.com/app_50000005/page/3000000356?sessionKey=third_party:session_key:15225745513&mobile=15225745513&userId=FengTengFei'
        function getParameterByName(name, url = window.location.href) {
            name = name.replace(/[\[\]]/g, '\\$&')
            var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
                results = regex.exec(url)
            if (!results) return null
            if (!results[2]) return ''
            return decodeURIComponent(results[2].replace(/\+/g, ' '))
        }
        stateForm.sessionKey = getParameterByName('sessionKey', currentURL)
        stateForm.userId = getParameterByName('userId', currentURL)
        stateForm.mobile = getParameterByName('mobile', currentURL)
        // 获取当前页面url的传参
        async function getTenantId() {
            try {
                debuggerState.two.status = '第二步获取tenantId开始'
                let firstSlashIndex = currentURL.indexOf('/', 8)
                let prefix

                if (firstSlashIndex !== -1) {
                    prefix = currentURL.substring(0, firstSlashIndex)
                    let protocols = ['http://', 'https://']
                    let protocol = protocols.find(p => prefix.includes(p))

                    if (protocol) {
                        let result = prefix.substring(protocol.length)
                        result = result + '/app_50000005/'
                        console.log(result, 'result')
                        let data = await post(`/base/api/v1/product/url`, {
                            url: result
                            // url: 'ppm-stage.allintechinc.com'
                        })
                        if (data.status === 'success') {
                            // 获取到的tenantId
                            stateForm.tenantId = data.data.tenantId
                            stateForm.productId = data.data.id
                            // 成功获取之后登陆操作
                            debuggerState.two.content = `第二步成功-----tenantId是${data.data.tenantId},productId是${data.data.id}`
                            getToken()
                        } else {
                            console.error('获取tenantId失败')
                            debuggerState.two.content = `获取tenantId失败${data.errorMsg},传值是${result}`
                        }
                    } else {
                        console.error('未找到 `http://` 或 `https://`')
                    }
                } else {
                    console.error('无法提取前缀')
                }
            } catch (error) {
                console.error('getTenantId出现错误:', error)
            }
        }
        async function getToken() {
            try {
                debuggerState.five.status = '第五步登录获取信息'
                let uuid = ''
                let token = ''
                const params = {
                    sessionKey: stateForm.sessionKey,
                    mobile: stateForm.mobile,
                    appId: 'product-container',
                    withTenantIdFlag: false,
                    mobileIsUserName: false,
                    tenantId: stateForm.tenantId
                }
                let result = await post('/base/api/v1/open/login', params)
                console.log(result.status, 'getTokenstatus')
                if (result.data) {
                    console.log(result, '登陆接口返回')
                    debuggerState.five.content = `第五步登录获取信息--登陆接口返回${result}`
                    let newUserData = {
                        uuid: result.data.uuid,
                        token: result.data.token,
                        productId: stateForm.productId,
                        tenantId: stateForm.tenantId,
                        appid: 'product-container'
                    }
                    localStorage.setItem('app-user-store', JSON.stringify(newUserData))
                    localStorage.setItem('app-user', JSON.stringify(newUserData))
                    localStorage.setItem(
                        'al__Access-Token',
                        JSON.stringify({
                            expire: new Date().getTime(),
                            value: result.data.token
                        })
                    )
                    localStorage.setItem(
                        'al__UID',
                        JSON.stringify({
                            expire: new Date().getTime(),
                            value: result.data.uuid
                        })
                    )
                    uuid = result.data.uuid
                    token = result.data.token
                    console.log('登录后执行跳转')
                    debuggerState.five.status = '第五步登录获取信息--跳转成功'
                  setTimeout(() => {
                    window.location.href = `${import.meta.env.VITE_PUBLIC_PATH}/page/3000000356`
                  }, 2000)
                } else {
                    console.error('getToken出现错误:')
                    debuggerState.five.content = `第五步登录获取信息--失败${result.errorMsg}`
                }
            } catch (error) {
                console.error('getToken出现错误:', error)
                message.error('登录失败', error)
                debuggerState.five.content = `第五步登录获取信息--失败${error}`
            }
        }
        getTenantId()
        onMounted(() => {
            localStorage.removeItem('app-user-store')
            localStorage.removeItem('app-user')
            console.log('清除')
            console.log(localStorage.getItem('app-user-store'))
        })
</script>
<style lang="less" scoped>
  .page_root {
  width: 100%;
  height: 100%;
  overflow: auto;
  }
  .page_root :deep(.@{ant-prefix}-spin-nested-loading),
  .page_root :deep(.@{ant-prefix}-spin-container)
   {
      height: 100%;
  }
  .page_root :deep(.@{ant-prefix}-spin-container .@{ant-prefix}-table-wrapper)
   {
      display: flex;
      flex-flow: column nowrap;
      justify-content: flex-start;
  }
  .page_root :deep(.@{ant-prefix}-table)
   {
    flex: auto;
    overflow: auto;
  }
  .table-moreBtn_down {
    overflow: hidden; white-space: nowrap; text-overflow: ellipsis; width: 100px;
  }

  .table-moreBtn_menu :deep(.table-moreBtn_menu-item):hover {
    background: #ebf1ff;
  }

  /*  表格树结构样式处理，展开按钮层级增加*/
  :deep(.@{ant-prefix}-table-row-expand-icon) {
    z-index: 1;
  }
  /*  表格树结构 由于每个表格项采用自定义组件，使用绝对定位布局，开启树结构导致显示异常，暂时使用层级定位位置 */
  :deep(.@{ant-prefix}-table-row-level-1 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
    left: 15px !important;
    width: calc(100% - 15px);
  }
  :deep(.@{ant-prefix}-table-row-level-2 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
    left: 30px !important;
    width: calc(100% - 30px);
  }
  :deep(.@{ant-prefix}-table-row-level-3 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
    left: 45px !important;
    width: calc(100% - 45px);
  }
  :deep(.@{ant-prefix}-table-row-level-4 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
    left: 60px !important;
    width: calc(100% - 60px);
  }

  /* 穿梭框改变默认样式，为根据组件样式控制左右栏宽度。 */
  :deep(.@{ant-prefix}-transfer-list)
   {
      height: 100%;
      width: 50%;
  }
</style>